package com.xiaoyu.lanling.data

import `in`.srain.cube.app.init.InitializableAsync
import `in`.srain.cube.app.lifecycle.AppActivityLifecycleCallbacks
import `in`.srain.cube.util.NetworkStatusManager
import android.content.Context
import android.content.Intent
import com.xiaoyu.base.data.UserData
import com.xiaoyu.base.event.NoReceiverJsonEvent
import com.xiaoyu.base.net.RequestCreator
import com.xiaoyu.lanling.common.config.HttpConfig
import com.xiaoyu.lanling.feature.setting.util.NotificationUtil
import java.util.concurrent.ExecutorService
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit

class AppStateData private constructor() : AppActivityLifecycleCallbacks.OnLifecycleListener, NetworkStatusManager.OnNetworkChangeListener, InitializableAsync {

    companion object {
        val instance by lazy { AppStateData() }
    }

    private val mThreadPoolExecutor: ExecutorService = ThreadPoolExecutor(0, 1, 0L, TimeUnit.MILLISECONDS, LinkedBlockingQueue())

    init {
        AppActivityLifecycleCallbacks.getInstance().addLifecycleListener(this)
        NetworkStatusManager.getInstance().addOnNetworkChangeListener(this)
    }

    @Volatile
    private var mUpdateWhenNetworkConnected = false

    private val isNetworkConnected: Boolean
        get() = NetworkStatusManager.getInstance().isConnected

    override fun onAppToForeground() {
        updateAppState()
        NotificationUtil.instance.dismissNotification()
    }

    override fun onAppToBackground() {
        updateAppState()
        NotificationUtil.instance.showNotificationIfNeed()
    }

    override fun onNetworkChange(intent: Intent) {
        if (isNetworkConnected && mUpdateWhenNetworkConnected) {
            updateAppState()
        }
    }

    fun onAppStartOrLogin() { // temp
        if (UserData.getInstance().hasLogin()) {
            updateAppState()
        }
    }

    fun updateAppState() {
        mThreadPoolExecutor.submit { updateAppStateSync() }
    }

    private fun updateAppStateSync() {
        if (!UserData.getInstance().hasLogin()) {
            return
        }
        if (!isNetworkConnected) {
            mUpdateWhenNetworkConnected = true
            return
        }
        mUpdateWhenNetworkConnected = false
        val requestCreator = RequestCreator.create<NoReceiverJsonEvent>(Any(), NoReceiverJsonEvent::class.java)
                .setRequestUrl(HttpConfig.LANLING_ONLINE_STATE)
                .addQueryData("state", if (AppActivityLifecycleCallbacks.getInstance().isAppInForeground) 1 else 0)

        try {
            requestCreator.requestSync()
        } catch (throwable: Throwable) {
            throwable.printStackTrace()
        }
    }

    override fun initiateAsync(context: Context) {
        onAppStartOrLogin()
    }
}